package com.zzh.takeoutapp.behaviors;


import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.github.florent37.viewanimator.AnimationListener;
import com.github.florent37.viewanimator.ViewAnimator;
import com.zzh.takeoutapp.R;

public class DetailHeaderBehavior extends AppBarLayout.Behavior implements AppBarLayout.OnOffsetChangedListener, GestureDetector.OnGestureListener {
    public boolean canDrag;
    private AppBarLayout dhv;
    private Toolbar toolbar;
    private Context mContext;
    private TextView toolbar_title;
    private int scaleOffset = -1;
    private int pWidth, offSet;
    private MotionEvent mov;
    private View car_fl;
    private GestureDetector mGestureDetector;
    private ViewAnimator carAnim;
    private static final int TOP_CHILD_FLING_THRESHOLD = 3;

    public DetailHeaderBehavior() {
        super();
    }

    public DetailHeaderBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setDragCallback(new DragCallback() {
            @Override
            public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                return true;
            }
        });
    }

    @Override
    public boolean layoutDependsOn(CoordinatorLayout parent, AppBarLayout child, View dependency) {
        mGestureDetector = new GestureDetector(this);
        return super.layoutDependsOn(parent, child, dependency);
    }

    @Override
    public boolean onLayoutChild(CoordinatorLayout parent, AppBarLayout abl, int layoutDirection) {
        boolean handled = super.onLayoutChild(parent, abl, layoutDirection);
        if (toolbar == null) {
            car_fl = parent.findViewById(R.id.car_mainfl);
            car_fl.setTranslationY(mContext.getResources().getDimension(R.dimen.shopcar_height));
            toolbar = abl.findViewById(R.id.toolbar);
            toolbar_title = abl.findViewById(R.id.toolbar_title);
            toolbar_title.setTranslationY(abl.getTotalScrollRange());
            dhv = abl;
            dhv.addOnOffsetChangedListener(this);
            pWidth = parent.getWidth();
        }
        dhv.offsetTopAndBottom(scaleOffset);
        return handled;
    }

    @Override
    public boolean onDependentViewChanged(CoordinatorLayout parent, AppBarLayout child, View dependency) {
        return super.onDependentViewChanged(parent, child, dependency);
    }

    @Override
    public boolean onInterceptTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
        judgeDrag();
        if (!canDrag) {
            if (ev.getRawX() < dhv.getLeft() || ev.getRawX() > dhv.getRight() || ev.getRawY() < dhv.getTop() || ev.getRawY() > dhv.getBottom()) {
                ((Activity) mContext).finish();
                ((Activity) mContext).overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            } else {
                mGestureDetector.onTouchEvent(ev);
            }
        } else {
        }
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mGestureDetector.onTouchEvent(ev);
                break;
            case MotionEvent.ACTION_UP:
                onActionUp(ev);
                mGestureDetector.onTouchEvent(ev);
                break;
        }
        return canDrag && super.onInterceptTouchEvent(parent, child, ev);
    }

    @Override
    public boolean onTouchEvent(CoordinatorLayout parent, AppBarLayout child, MotionEvent ev) {
        judgeDrag();
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mGestureDetector.onTouchEvent(ev);
                break;
            case MotionEvent.ACTION_MOVE:
                if (mov != null) {
                    mov.recycle();
                    mov = null;
                }
                return super.onTouchEvent(parent, child, ev);
            case MotionEvent.ACTION_UP:
                onActionUp(ev);
                break;
        }
        return super.onTouchEvent(parent, child, ev);
    }

    private int animState = 0;//0 normal 1 uping  2 downing

    private void judgeDrag() {
        canDrag = dhv.getWidth() == pWidth;
        if (canDrag && car_fl.getTranslationY() > 0 && animState != 1) {
            if (carAnim != null && animState == 2) {
                carAnim.cancel();
            }
            animState = 1;
            carAnim = ViewAnimator.animate(car_fl).onStop(new AnimationListener.Stop() {
                @Override
                public void onStop() {
                    animState = 0;
                }
            }).translationY(car_fl.getTranslationY(), 0).duration(200).start();
        } else if (!canDrag && car_fl.getTranslationY() < car_fl.getHeight() && animState != 2) {
            if (carAnim != null && animState == 1) {
                carAnim.cancel();
            }
            animState = 2;
            carAnim = ViewAnimator.animate(car_fl).onStop(new AnimationListener.Stop() {
                @Override
                public void onStop() {
                    animState = 0;
                }
            }).translationY(car_fl.getTranslationY(), car_fl.getHeight()).duration(200).start();
        }
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        offSet = verticalOffset;
        if (dhv == null) {
            return;
        }
        if (dhv.getTotalScrollRange() + verticalOffset < 100) {
            toolbar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.yellow));
        } else {
            toolbar.setBackgroundColor(ContextCompat.getColor(mContext, R.color.transparent));
        }
        toolbar_title.setTranslationY(dhv.getTotalScrollRange() + verticalOffset);
    }


    @Override
    public boolean onDown(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent motionEvent) {

    }

    private void onActionUp(MotionEvent motionEvent) {
    }

    @Override
    public boolean onSingleTapUp(MotionEvent motionEvent) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent motionEvent) {

    }

    @Override
    public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
        return false;
    }


    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
        if (target.getId() == R.id.car_recyclerview) {
            return;
        }
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
    }

    @Override
    public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dxConsumed, int dyConsumed, int
            dxUnconsumed, int dyUnconsumed) {
        if (target.getId() == R.id.car_recyclerview) {
            return;
        }
        super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed);
    }

    @Override
    public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean
            consumed) {
        if (target.getId() == R.id.car_recyclerview) {
            return true;
        }
        if (target instanceof RecyclerView && velocityY < 0) {
            final RecyclerView recyclerView = (RecyclerView) target;
            final View firstChild = recyclerView.getChildAt(0);
            final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
            consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD;
        }
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    }

    public void setDragable(final boolean canDrag) {
        setDragCallback(new DragCallback() {
            @Override
            public boolean canDrag(@NonNull AppBarLayout appBarLayout) {
                return canDrag;
            }
        });
    }
}
